<template>
    <div class="page">
        <div class="video-box">
            <table align="center">
                <tr>
                    <td>视频窗口</td>
                    <td></td>
                    <td>推理结果</td>
                </tr>
                <tr>
                    <td style="padding:0 20px;">
                        <video class="video" id="video" controls autoplay>
                            Your browser is too old which doesn't support HTML5 video.
                        </video>
                    </td>
                    <td style="padding:0 20px;">
                    </td>
                    <td style="padding:0 20px;">
                      <canvas class="canvas" id='V2I_canvas' width="900px" height="600px"></canvas>
                    </td>
                </tr>
            </table>
        </div>
    </div>
</template>

<script>
import flvjs from 'flv.js'
export default {
  data () {
    return {
      camera: {
        id: '',
        name: ''
      },
      video_mode: 'yoloV3',
      video_img: '',
      video_url: '',
      address: '',
      deploying: false,
      deploying_time: 0, // 部署等待时间
      undeploying: false,
      deploy_status: 0, // 0=未部署，1=已部署
      ports: {
        images: '',
        camera: ''
      },
      host: 'http://10.0.104.161', // 临时测试用的
      logs: [],
      logs_view: false,
      logs_view_src: '',
      destroy: false,
      wss: '',
      websocket_url: ''
    }
  },
  created () {
    this.video_url = 'http://10.5.26.85:7070/live?app=hls&stream=test'
    this.videoInit()

    this.websocket_url = 'ws://10.0.104.210:9443/ws'
    this.initWebSocket()
  },
  beforeDestroy () {
    this.destroy = true
  },
  mounted () {

  },
  computed: {

  },
  methods: {
    videoInit () {
      let that = this
      if (that.destroy) {
        // 页面已销毁
        return
      }
      setTimeout(() => {
        if (flvjs.isSupported()) {
          if (typeof that.video_player !== 'undefined') {
            if (that.video_player != null) {
              that.video_player.pause()
              that.video_player.unload()
              that.video_player.detachMediaElement()
              that.video_player.destroy()
              that.video_player = null
            }
          }

          var videoElement = document.getElementById('video')
          console.log('Play: ' + that.video_url)
          that.video_player = flvjs.createPlayer({
            type: 'flv',
            isLive: true,
            url: that.video_url,
            reuseRedirectedURL: true
          })
          that.video_player.attachMediaElement(videoElement)
          that.video_player.load()
          that.video_player.play()
          that.video_player.on('error', err => {
            console.log('Player On Error:', err)
            // 出错重新加载
            setTimeout(() => {
              that.videoInit()
            }, 2000)
          })
        }
      }, 300)
      setTimeout(() => {
        that.getResult(0)
      }, 300)
    },
    initWebSocket () {
      let that = this
      if ('WebSocket' in window) {
        console.log('您的浏览器支持WebSocket')
        try {
          that.wss = new WebSocket(that.websocket_url) // 创建WebSocket连接
          this.wss.onmessage = this.websocketonmessage
          this.wss.onopen = this.websocketonopen
          this.wss.onerror = this.websocketonerror
          this.wss.onclose = this.websocketclose
        } catch (e) {
          console.log(`chorme do not support canvas! error: ${JSON.stringify(e)}`)
        }
      } else {
        console.log('您的浏览器不支持WebSocket' + `chorme  does not support WebSocket error 3`)
      }
    },
    websocketonopen () { // 连接建立之后执行send方法发送数据
      console.log('send hello')
      this.wss.send('hello')
    },
    websocketonerror () { // 连接建立失败重连
      this.initWebSocket()
    },
    websocketonmessage (msg) { // 数据接收
      // console.log('input: ', msg.data)
      var objectInfos = JSON.parse(msg.data)
      // console.log('output: ', objectInfos)
      this.getResult(0, objectInfos)
    },
    websocketsend (Data) { // 数据发送
      this.wss.send(Data)
    },
    websocketclose (e) { // 关闭
      console.log('断开连接', e)
    },
    getResult (time, objectInfos) {
      function containImg (sx, sy, box_w, box_h, source_w, source_h) {
        var dx = sx
        var dy = sy
        var dWidth = box_w
        var dHeight = box_h
        if (source_w > source_h || (source_w === source_h && box_w < box_h)) {
          dHeight = source_h * dWidth / source_w
          dy = sy + (box_h - dHeight) / 2
        } else if (source_w < source_h || (source_w === source_h && box_w > box_h)) {
          dWidth = source_w * dHeight / source_h
          dx = sx + (box_w - dWidth) / 2
        }
        return {
          dx,
          dy,
          dWidth,
          dHeight
        }
      }

      // var video = document.getElementById('video')
      var video = document.querySelector('video')
      // console.log(video)
      var tmpCanvas = document.getElementById('V2I_canvas')
      if (!tmpCanvas.getContext) {
        alert('您的浏览器暂不支持canvas')
      } else {
        // console.log('video.width: ', video.width, 'video.height: ', video.height, 'video.videoWidth: ', video.videoWidth, 'video.videoHeight: ', video.videoHeight, 'canvas.offsetWidth: ', canvas.offsetWidth)
        // tmpCanvas.width = video.videoWidth
        // tmpCanvas.height = video.videoHeight
        var context = tmpCanvas.getContext('2d')
        context.strokeStyle = '#FF0000'
        context.font = '30px serif'
        context.fillStyle = '#FF0000'
        var imgRect = containImg(0, 0, tmpCanvas.width, tmpCanvas.height, video.videoWidth, video.videoHeight)
        // console.log('tmpCanvas.width: ', tmpCanvas.width, 'tmpCanvas.height: ', tmpCanvas.height, 'tmpCanvas.offsetWidth: ', tmpCanvas.offsetWidth, 'tmpCanvas.offsetHeight: ', tmpCanvas.offsetHeight, 'imgRect:', imgRect)
        // context.drawImage(video, 0, 0, tmpCanvas.offsetWidth, video.videoHeight * tmpCanvas.offsetWidth / video.videoWidth)
        context.drawImage(video, imgRect.dx, imgRect.dy, imgRect.dWidth, imgRect.dHeight)
        if (objectInfos != null) {
          var objects = objectInfos['Objects']
          for (let i = 0; i !== objectInfos['Amount']; i++) {
            var ob = objects[i]
            ob['X'] = ob['X'] / video.videoWidth * imgRect.dWidth + imgRect.dx
            ob['Y'] = ob['Y'] / video.videoHeight * imgRect.dHeight + imgRect.dy
            ob['Width'] = ob['Width'] / video.videoWidth * imgRect.dWidth
            ob['Hight'] = ob['Hight'] / video.videoHeight * imgRect.dHeight
            var leftX = ob['X'] - ob['Width'] / 2
            var leftY = ob['Y'] - ob['Hight'] / 2
            context.strokeRect(leftX, leftY, ob['Width'], ob['Hight'])
            context.fillText(ob['Object'], leftX, leftY)
          }
        }
      }
    }
  }
}
</script>

<style scoped>
.handle-box{
    padding:10px;
    border: 1px solid #EBEEF5;
    border-top: 0;
    border-bottom: 0;
}
.handle-box > button{
    margin:0 5px 0 0;
}
.handle-input{
    width: 300px;
    display: inline-block;
}
button{
    cursor: pointer;
}
.video-box{
    padding:20px;
    border: 1px solid #EBEEF5;
}
.video{
    width: 900px;
    height: 600px;
    background: #333;
    display: inline-block;
}
.canvas{
  width: 900px;
  height: 600px;
  background: #333;
}
</style>
